import axios from 'axios';
import { ElMessage } from 'element-plus';
const baseURL = '/api';
const instance = axios.create({baseURL})
import router from "../router/index.js";
import {useUserStore} from '@/stores/user.js'
const userStore=useUserStore();
//添加响应拦截器
instance.interceptors.response.use(
    result=>{
        if(result.data.code==0){return result.data;}
        ElMessage.error(result.data.message?result.data.message:'服务异常');
        return Promise.reject(result.data);},
    err=>{
        if(err.response.status==401){
            ElMessage.error('请先登录');router.push('/login');}
        else{ElMessage.error('服务异常');}
    }
)
//请求拦截器
instance.interceptors.request.use(
    (config)=>{
        if(userStore.token){config.headers.Authorization=userStore.token;}
        return config;
    },
    err=>{Promise.reject(err);}
)
export default instance;